package com.bit.web;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    private Socket socket = null;

    public TCPEchoClient(String serverIP,int serverPort) throws IOException {
        //实例化过程就是建立了pcb连接
        socket = new Socket(serverIP,serverPort);
    }
    public void start(){
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))){
        while(true){
            System.out.println("->");
            //读取用户输入的内容
            String request = scanner.nextLine();
            if("exist".equals(request)){
                break;
            }
            //构造请求并发送
            bufferedWriter.write(request);
            bufferedWriter.flush();
            //读取响应数据
            String response = bufferedReader.readLine();
            //把响应数据显示在界面上
            System.out.println(response);
        }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
